﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;

namespace DMSClient
{
    public partial class frmImportStock : Form
    {
        WSHttpBinding httpBinding = new WSHttpBinding();
        EndpointAddress address = new EndpointAddress(Properties.Settings.Default.Server);
        
        DataTable dt;
        string ambiente;
        string ambienteDes;
        
        public frmImportStock()
        {
            InitializeComponent();
            ambiente = Properties.Settings.Default.CurrentEnv;
            ambienteDes = Properties.Settings.Default.CurrentEnvDes;
            httpBinding.MaxReceivedMessageSize = 2147483647;
            httpBinding.MaxBufferPoolSize = 2147483647;
            httpBinding.CloseTimeout = TimeSpan.MaxValue;
            httpBinding.ReceiveTimeout = TimeSpan.MaxValue;
            httpBinding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
            httpBinding.Security.Mode = SecurityMode.None;
            DMSServices.DMSServicesClient cliente = new DMSClient.DMSServices.DMSServicesClient(httpBinding, address);
            this.Text = ambienteDes + " - ImportStock";

            dtpEndDate.Value = DateTime.Now;
            dtpStarDate.Value = DateTime.Now.AddMonths(-1);
            uceDistributors.DisplayMember = "cdOrgUnit";
            uceDistributors.ValueMember = "idOrgUnit";

            string distributors = null;
            try
            {
                cliente.Open();
                distributors = cliente.getDistributorsList(ambiente);
                cliente.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ex.InnerException);
            }
            if (distributors == null)
            {
                throw new Exception(Properties.Settings.Default.DistributorsNullListErrorMsg);
            }
            DataTable dt = new DataTable("dtDistributorsList");
            dt.Columns.Add("idOrgUnit");
            dt.Columns.Add("cdOrgUnit");

            DataSet ds = new DataSet();
            ds.Tables.Add(dt);

            System.IO.StringReader xmlSR = new System.IO.StringReader(distributors);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            uceDistributors.DataSource = ds.Tables[0];
            uceDistributors.SelectedIndex = 0;
            xmlSR.Close();


        }

        private void bSearch_Click(object sender, EventArgs e)
        {
            ugStock.DataSource = null;
            backgroundWorker1.RunWorkerAsync();
            cambio(false);
        }

        private void cambio(bool estado)
        {
            uceDistributors.Enabled = estado;
            dtpStarDate.Enabled = estado;
            dtpEndDate.Enabled = estado;
            ugStock.Enabled = estado;
            bSearch.Enabled = estado;
            ubExport.Enabled = estado;
            loader1.Visible = !estado;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            string listaStock = null;
            DMSServices.DMSServicesClient cliente = new DMSClient.DMSServices.DMSServicesClient(httpBinding, address);
            try
            {
                cliente.Open();
                listaStock = cliente.getStockReport(uceDistributors.Value.ToString(), DateTime.Parse(dtpStarDate.Value.ToString()), DateTime.Parse(dtpEndDate.Value.ToString()), ambiente);
                cliente.Close();
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex) {
                throw new Exception(Properties.Settings.Default.ReportErrorMsg, ex.InnerException);
            }
            if (listaStock == null) throw new Exception(Properties.Settings.Default.ReportNullErrorMsg);

            dt = new DataTable("Stockdt");
            dt.Columns.Add("cdProduct");
            dt.Columns.Add("cdWarehouse");
            dt.Columns.Add("vlBeginningMonthAmount", typeof(Double));
            dt.Columns.Add("vlBeginningMonthQuantity", typeof(Double));
            dt.Columns.Add("vlReceivedQuantity", typeof(Double));
            dt.Columns.Add("vlDispatchedQuantity", typeof(Double));
            dt.Columns.Add("dtStock");
            dt.Columns.Add("cdStatus");
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);

            System.IO.StringReader xmlSR = new System.IO.StringReader(listaStock);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    cambio(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                ugStock.DataSource = dt;
                ugStock.DisplayLayout.Bands[0].Columns["vlBeginningMonthAmount"].CellAppearance.TextHAlign = Infragistics.Win.HAlign.Right;
                ugStock.DisplayLayout.Bands[0].Columns["vlBeginningMonthQuantity"].CellAppearance.TextHAlign = Infragistics.Win.HAlign.Right;
                ugStock.DisplayLayout.Bands[0].Columns["vlReceivedQuantity"].CellAppearance.TextHAlign = Infragistics.Win.HAlign.Right;
                ugStock.DisplayLayout.Bands[0].Columns["vlDispatchedQuantity"].CellAppearance.TextHAlign = Infragistics.Win.HAlign.Right;
                cambio(true);
            }
        }

        private void frmImportStock_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (backgroundWorker1.IsBusy)
            {
                backgroundWorker1.CancelAsync();
            }
        }

        private void ubExport_Click(object sender, EventArgs e)
        {
            if (ugStock.Rows.Count < 1)
            {
                MessageBox.Show(this, "There is no data to export", "Stock Report", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            System.Windows.Forms.SaveFileDialog dialogo = new System.Windows.Forms.SaveFileDialog();
            dialogo.DefaultExt = "xls";
            Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter Exporter = new Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter();
            if (dialogo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Exporter.Export(ugStock, dialogo.FileName);
                if (MessageBox.Show(this, "Do you want to open the file?", "Stock Report", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(dialogo.FileName);
                }
            }
        }

        private void centrarLoader(){
            loader1.Left = (this.Width - loader1.Width) / 2;
            loader1.Top = ((this.Height - loader1.Height) / 2) - loader1.Height;
        }

        private void frmImportStock_Shown(object sender, EventArgs e)
        {
            centrarLoader();
        }

        private void frmImportStock_Resize(object sender, EventArgs e)
        {
            centrarLoader();
        }
    }
}
